package com.yejiarong.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiarong.auth.bean.entity.User;
import com.yejiarong.auth.mapper.IRoleMapper;
import com.yejiarong.auth.mapper.IUserMapper;
import com.yejiarong.common.constant.CommonConstants;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author YeJR
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final IUserMapper userMapper;

    private final IRoleMapper roleMapper;

    public UserDetailServiceImpl(IUserMapper userMapper, IRoleMapper roleMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username).last(CommonConstants.LIMIT1));
        if (user == null) {
            throw new UsernameNotFoundException("此账号不存在");
        }

        // 查询角色
        List<String> roles = Optional.ofNullable(roleMapper.getUserRoles(user.getId())).orElseGet(ArrayList::new);
        roles = roles.stream().map(role -> CommonConstants.ROLE_PREFIX + role).toList();
        // 构建权限集合
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                        user.getStatus() == 1, true, true,
                user.getStatus() != 3, authorities);
    }

}
